package com.sgb.kjwl.viewmodel.self;

import android.content.Intent;

import androidx.databinding.ObservableField;

import android.widget.Toast;





import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.UserAuthMsgEntity;
import com.sgb.link.entity.PickFilterEntity;
import com.swgk.core.base.api.ICallBack;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.AuthPhotoEntity;
import com.sgb.kjwl.model.entity.user.SupplierAuthEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.fragment.self.EnterpriseRegistrationFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterModelE extends BaseViewModel {
    /* public ObservableField<String> account = new ObservableField<>("");
     public ObservableField<String> pwd = new ObservableField<>("");
     public ObservableField<String> code = new ObservableField<>("");
     public ObservableField<Boolean> agree = new ObservableField<>(false);*/
    public ObservableField<SupplierAuthEntity> supplierAuthEntity = new ObservableField<>(new SupplierAuthEntity());
    public ObservableField<SupplierAuthEntity.UserDTO> person = new ObservableField<>(new SupplierAuthEntity.UserDTO());
    private EnterpriseRegistrationFragment enterpriseRegistrationFragment;
    private SelfRepertory repertory;


    public RegisterModelE(EnterpriseRegistrationFragment enterpriseRegistrationFragment, SelfRepertory repertory) {
        this.enterpriseRegistrationFragment = enterpriseRegistrationFragment;
        this.repertory = repertory;
    }

    //上传营业执照
    public void upLicenseModel(File file) {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        APIManager.getInstance().getUploadAPI().uploadPhoto(photos).enqueue(new Callback<BaseEntity<AuthPhotoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<AuthPhotoEntity>> call, Response<BaseEntity<AuthPhotoEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() != null && response.body().getState().equals("ok")) {
                    if (response.body().getData() != null) {
                        supplierAuthEntity.get().setLicenseUrl(response.body().getData().getImageUrl());
                        if (!"0".equals(response.body().getData().getRecognition())) {
                            Toast.makeText(enterpriseRegistrationFragment.getActivity(), "正在处理，请稍后！", Toast.LENGTH_SHORT).show();
                            supplierAuthEntity.get().setBusiness(response.body().getData().getBusiness());
                            supplierAuthEntity.get().setRegisteredCapital(response.body().getData().getCapital());
                            supplierAuthEntity.get().setEstablishmentDate(response.body().getData().getEstablish_date());
                            supplierAuthEntity.get().setCompanyName(response.body().getData().getName());
                            supplierAuthEntity.get().setLegalPerson(response.body().getData().getPerson());
                            supplierAuthEntity.get().setCreditCode(response.body().getData().getReg_num());
                            supplierAuthEntity.get().setBusinessTerm(response.body().getData().getValid_period());
                            enterpriseRegistrationFragment.uploadSuccess(supplierAuthEntity.get());
                        } else {
                            supplierAuthEntity.get().setBusiness("");
                            supplierAuthEntity.get().setRegisteredCapital("");
                            supplierAuthEntity.get().setEstablishmentDate("");
                            supplierAuthEntity.get().setCompanyName("");
                            supplierAuthEntity.get().setLegalPerson("");
                            supplierAuthEntity.get().setCreditCode("");
                            supplierAuthEntity.get().setBusinessTerm("");
                        }
                    } else {
//                        enterpriseRegistrationFragment.removeList();
//                        Toast.makeText(enterpriseRegistrationFragment.getActivity(), "营业执照识别失败，请重新上传！", Toast.LENGTH_SHORT).show();
                    }
                } else {
//                    enterpriseRegistrationFragment.removeList();
//                    MToast.showToast(enterpriseRegistrationFragment.getActivity(), "营业执照识别失败，请重新上传！");
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<AuthPhotoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                enterpriseRegistrationFragment.removeList();
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "上传失败，请重新上传！");
            }
        });
    }

    //上传营业执照//只上传图片 不进行内容识别
    public void upLicenseModel2(File file) {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() != null && response.body().getState().equals("ok")) {
                    if (response.body().getData() != null) {
                        //bugly上面包toast行空指针
                        if (enterpriseRegistrationFragment != null) {
                            Toast.makeText(enterpriseRegistrationFragment.getActivity(), "上传成功!", Toast.LENGTH_SHORT).show();
                        }
                        supplierAuthEntity.get().setLicenseUrl(response.body().getData().toString());

//                        enterpriseRegistrationFragment.uploadSuccess(supplierAuthEntity.get());
                    } else {
                        if (enterpriseRegistrationFragment != null) {
                            enterpriseRegistrationFragment.removeList();
                            Toast.makeText(enterpriseRegistrationFragment.getActivity(), "营业执照识别失败,请重新上传!", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    if (enterpriseRegistrationFragment != null) {
                        enterpriseRegistrationFragment.removeList();
                        MToast.showToast(enterpriseRegistrationFragment.getActivity(), "营业执照识别失败,请重新上传!");
                    }
                }

            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "营业执照识别失败,请重新上传!");
            }
        });
    }


    public void getCompanyTypeModel() {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUserAPI().getCompanyType().enqueue(new Callback<BaseEntity<List<String>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<String>>> call, Response<BaseEntity<List<String>>> response) {
                if (response.body() == null) return;

                DialogHelper.dismissProgressDialog();
                enterpriseRegistrationFragment.showTypePop(response.body().getData());

            }

            @Override
            public void onFailure(Call<BaseEntity<List<String>>> call, Throwable t) {

            }
        });
    }


    //企业服务类型
    public void getCompanyTypes() {
//        APIManager.getInstance().getBusinessManagementAPI().queryCompanyServiceType().enqueue(new Callback<BaseEntity<List<ComPanyServiceEntity>>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<List<ComPanyServiceEntity>>> call, Response<BaseEntity<List<ComPanyServiceEntity>>> response) {
//                if (response.body() == null || response.body().getState() == null) {
//                    return;
//                }
//                enterpriseRegistrationFragment.setCompanyTypes(response.body().getData());
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<List<ComPanyServiceEntity>>> call, Throwable t) {
//
//            }
//        });
        APIManager.getInstance().getBusinessManagementAPI().getNewServiceType(1).enqueue(new ICallBack<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>> data) {
                if (data != null && data.getData() != null){
                    enterpriseRegistrationFragment.setCompanyTypes(data.getData());
                }

            }
        });
    }


    public void commitCompanyAuth() {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUserAPI().identificationCompany(supplierAuthEntity.get()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    MToast.showLongToast(enterpriseRegistrationFragment.getActivity(), "您的认证申请已提交成功，平台将在一个工作日内完成审核，请耐心等待！");
                    // enterpriseRegistrationFragment.loginSucceed(response.body().getData(), supplierAuthEntity.get().getPersonDTO().getMobile());
                    enterpriseRegistrationFragment.commitCompanyAuthSuccess();
                } else {
                    MToast.showToast(enterpriseRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "提交失败，稍后请重试");
            }
        });
    }

    public void companyAuthDetail(String companyId) {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUserAPI().companyAuthDetail(companyId).enqueue(new ICallBack<BaseEntity<SupplierAuthEntity>>() {
            @Override
            public void onSuccess(BaseEntity<SupplierAuthEntity> data) {
                supplierAuthEntity.set(data.getData());
                enterpriseRegistrationFragment.getAuthInfo(data.getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<SupplierAuthEntity>> call, Throwable t) {
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "提交失败，稍后请重试");
            }
        });
    }


    public void getCodeModel() {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUserAPI().getNewRegisterCode(supplierAuthEntity.get().getUserDTO().getTelPhone()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if ("ok".equals(response.body().getState())) {
                    enterpriseRegistrationFragment.getCodeSuccess();
                } else {
                    MToast.showToast(enterpriseRegistrationFragment.getActivity(), "" + response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), t.getMessage());
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    public void getAddressModel() {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                enterpriseRegistrationFragment.showAddressPop(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void pwdLoginModel(String mobile, String pwd) {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "登录中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getUserAPI().login(mobile, pwd).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
//                    saveUserInfo(response.body().getData());
//                    repertory.saveAccount(mobile);
//                    MToast.showToast(activity, "登录成功");
//                    activity.loginSucceed(response.body().getData(), mobile);
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, mobile);
//                    JPushInterface.setAlias(activity, 1, mobile);
//                    getUserInfo();
                    loginImModel(response, mobile);
                } else {
                    DialogHelper.dismissProgressDialog();
                    MToast.showToast(enterpriseRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(enterpriseRegistrationFragment.getActivity(), t.getMessage());
            }
        });
    }


    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response, String mobile) {
        // 保存 token TODO
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, response.body().getData().getResourcePCToken());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, response.body().getData().getResourceAPPToken());

//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                saveUserInfo(response.body().getData());
                repertory.saveAccount(mobile);
                // MToast.showToast(.getActivity(), "登录成功");
                Toast.makeText(enterpriseRegistrationFragment.getActivity().getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, mobile);
                enterpriseRegistrationFragment.loginSucceed(response.body().getData(), mobile);
                JPushInterface.setAlias(enterpriseRegistrationFragment.getActivity(), 1, mobile);
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
////                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "账号信息异常,请联系管理员!");
//                Toast.makeText(enterpriseRegistrationFragment.getActivity().getApplicationContext(), "账号信息异常,请联系管理员!", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
////                MToast.showToast(enterpriseRegistrationFragment.getActivity(), "账号信息异常,请联系管理员!");
//                Toast.makeText(enterpriseRegistrationFragment.getActivity().getApplicationContext(), "账号信息异常,请联系管理员!", Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(enterpriseRegistrationFragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();

                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    enterpriseRegistrationFragment.getUserMsgSucceed(response.body().getData());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_AUTH, response.body().getData().isRelevance() ? "SUCCESS" : "NONE");
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PERSON_AUTH, response.body().getData().getPersonalAuth() == 1 ? true : false);
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.DRIVER_AUTH, response.body().getData().isDriverAuth() ? "SUCCESS" : "NONE");
                    EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_MAIN_INDEX, 0));
                    Intent intent = new Intent();
                    intent.putExtra("showPage", "FRAGMENT_SELF");
                    MainActivity.start(enterpriseRegistrationFragment.getActivity(), intent);
                } else {
                    MToast.showToast(enterpriseRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
